package com.wisdytech.common.websocket.handler;


import com.wisdytech.linkdcs.configuration.dto.ConfigurationEqDto;
import com.wisdytech.linkdcs.configuration.service.ITtEqConfigurationDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket通知类
 *
 * @author dlb
 */
public class WebSocketPushHandler extends TextWebSocketHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ITtEqConfigurationDataService configurationDataService;

    /**
     * 缓存websocekt列表
     */
    public static final ConcurrentHashMap<String, WebSocketSession> userSessionLists =
            new ConcurrentHashMap<>();

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

        String key = (String) session.getAttributes().get("time");
        if (session.isOpen()) {
            session.close();
        }
        if (userSessionLists.containsKey(key)) {
            userSessionLists.remove(key);
        }
        logger.info("用户退出系统。。。");
    }


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        logger.info("用户信息:" + session.getAttributes());

        Object time = session.getAttributes().get("time");
        if (null != time) {
            String key = (String) time;
            //缓存
            userSessionLists.put(key, session);
            String configurationId =(String) session.getAttributes().get("zutaiId");

            logger.info("建立连接立即推送数据...");
            List<ConfigurationEqDto> eqDtos=
                    configurationDataService.getEquipmentRealData(configurationId);
            configurationDataService.pushEquipmentData(eqDtos, session);
        }


    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String key = (String) session.getAttributes().get("time");

        logger.info("系统处理用户的请求信息。。。" + message.getPayload());
        //更新用户保存的组态信息
        if (userSessionLists.containsKey(key)) {
            //更新组态id
            userSessionLists.get(key).getAttributes().put("zutaiId", message.getPayload());
        }

    }


}
